<template>
  <div class="p-2">
    <div class="viewBox">
      <div class="title-item">
        <span class="line-box"></span><span>{{ title }}</span>
      </div>
      <el-form ref="studentFormRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="区县" prop="district">
          <el-cascader
            v-if="type != 2"
            clearable
            filterable
            placeholder="省/市/区"
            :options="addRessList"
            :props="cityProps"
            v-model="form.district"
            popper-class="pc-sel-area-cascader"
          />
          <!-- <el-input v-if="type != 2" v-model="form.district" placeholder="请输入区县" /> -->
          <div v-else>{{ getFullAddress(form.district) }}</div>
        </el-form-item>
        <el-form-item label="学校" prop="deptId" v-if="userId === 1 && tenantDisabled">
          <el-select v-if="type != 2 " v-model="form.deptId" placeholder="请选择学校" >
            <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
          </el-select>
          <div v-else> 
            {{getTenantById(tenantOptions,form.deptId)}}
          </div>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <!-- <el-input v-if="type != 2" v-model="form.grade" placeholder="请输入年级" /> -->
          <el-select v-model="form.grade" placeholder="请选择年级" v-if="type != 2">
            <el-option v-for="dict in sys_grade" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
          <div v-else>{{ form.grade }}</div>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <!-- <el-input v-if="type != 2" v-model="form.classId" placeholder="请输入班级" />
          <div v-else>{{ form.classId }}</div> -->
          <el-select v-model="form.classId" placeholder="请选择班级" v-if="type != 2">
            <el-option v-for="dict in classOptions" :key="dict.id" :label="dict.className" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级开始年度" prop="enrollmentYear">
          <el-input v-if="type != 2" v-model="form.enrollmentYear" placeholder="请输入班级开始年度" />
          <div v-else>{{ form.enrollmentYear }}</div>
        </el-form-item>

        <el-form-item label="学号" prop="stuId">
          <el-input v-if="type != 2" v-model="form.stuId" placeholder="请输入学号" />
          <div v-else>{{ form.stuId }}</div>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-if="type != 2" v-model="form.name" placeholder="请输入姓名" />
          <div v-else>{{ form.name }}</div>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别" v-if="type != 2">
            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
          <div v-else>{{ form.sex }}</div>
        </el-form-item>
        
        <el-form-item label="证件类型" prop="idType">
          <el-select v-model="form.idType" placeholder="请选择证件类型" v-if="type != 2">
            <el-option v-for="dict in core_id_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
          <div v-else><dict-tag :options="core_id_type" :value="form.idType" /></div>
        </el-form-item>
        <el-form-item label="证件号码" prop="idNo">
          <el-input v-if="type != 2" v-model="form.idNo" placeholder="请输入证件号码" />
          <div v-else>{{ form.idNo }}</div>
        </el-form-item>
        <el-form-item label="毕业年份" prop="graduateYear">
          <!-- <el-input v-if="type != 2" v-model="form.graduateYear" placeholder="请输入毕业年份" /> -->
          <el-select v-model="form.graduateYear" placeholder="请选择毕业年份" v-if="type != 2">
            <el-option v-for="dict in core_grad_year" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>

          <div v-else>{{ form.graduateYear }}</div>
        </el-form-item>
        
        <el-form-item label="照片" prop="images">
          <!-- <el-input v-if="type !=2" v-model="form.images" placeholder="请输入照片" /> -->
          <imageUpload v-model="form.images" v-if="type != 2" />
          <imageUpload v-model="form.images" v-else :isShowTip="false" class="imgView-box" />
        </el-form-item>
      </el-form>

      <div class="dialog-footer" v-if="type != 2">
        <el-button :loading="buttonLoading" type="primary" v-if="viewDisabled == false" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div class="dialog-footer" v-else>
        <el-button @click="cancel">返回</el-button>
      </div>
    </div>
    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <!-- <el-link  :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link> -->
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StudentADD" lang="ts">
import { listStudent, getStudent, delStudent, addStudent, updateStudent } from '@/api/core/student';
import { StudentVO, StudentQuery, StudentForm } from '@/api/core/student/types';
import { listClasses } from '@/api/core/classes';

import { globalHeaders } from '@/utils/request';
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { core_grad_year, core_id_type, sys_user_sex, sys_normal_disable, sys_grade } = toRefs<any>(
  proxy?.useDict('core_grad_year', 'core_id_type', 'sys_user_sex', 'sys_normal_disable', 'sys_grade')
);
import { getTenantById } from '@/utils/index';

import { listDept } from '@/api/system/dept'; //学校
import { DeptVO } from '@/api/system/dept/types'; //学校
import { get } from 'https';
import { useClassList,useTenantlList } from '@/composables/useSchoolList';

const studentList = ref<StudentVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const viewDisabled = ref(false);
const queryFormRef = ref<ElFormInstance>();
const studentFormRef = ref<ElFormInstance>();
const title = ref('');
const formId = ref('');
const type = ref<string | number>();
/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/core/student/import'
});
const uploadRef = ref<ElUploadInstance>();
//班级
// const { classOptions, fetchClasslList } = useClassList();
interface classOptionsType {
  id: number | string;
  className: string;
}
const classOptions = ref<classOptionsType[]>([]);

// 学校
interface DeptOptionsType {
  deptId: number | string;
  deptName: string;
  children: DeptOptionsType[];
}
const deptOptions = ref<DeptOptionsType[]>([]); //学校
//学校改租户数据
const { tenantOptions, fetchTenantlList,tenantDisabled} = useTenantlList()
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantId = ref(userStore.tenantId)

const initFormData: StudentForm = {
  name: undefined,
  sex: undefined,
  classId: undefined,
  grade: undefined,
  graduateYear: undefined,
  enrollmentYear: undefined,
  deptId: undefined,
  district: undefined,
  stuId: undefined,
  idType: undefined,
  idNo: undefined,
  images: undefined
};
const data = reactive<PageData<StudentForm, StudentQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    sex: undefined,
    classId: undefined,
    grade: undefined,
    graduateYear: undefined,
    enrollmentYear: undefined,
    deptId: undefined,
    district: undefined,
    idNo: undefined,
    images: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    sex: [{ required: true, message: '性别不能为空', trigger: 'change' }],
    classId: [{ required: true, message: '班级不能为空', trigger: 'blur' }],
    grade: [{ required: true, message: '年级不能为空', trigger: 'blur' }],
    graduateYear: [{ required: true, message: '毕业年份不能为空', trigger: 'blur' }],
    enrollmentYear: [{ required: true, message: '班级开始年度不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '学校不能为空', trigger: 'blur' }],
    district: [{ required: true, message: '区县不能为空', trigger: 'blur' }],
    stuId: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
    idType: [{ required: true, message: '证件类型不能为空', trigger: 'change' }],
    idNo: [
      { required: true, message: '证件号码不能为空', trigger: 'blur' },
      { max: 18, message: '证件号码不能超过18位', trigger: 'blur' }
    ],
    images: [{ required: true, message: '照片不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
import cityData from '@/assets/json/pca-code.json';
const addRessList = ref(cityData);
const cityProps = reactive({
  emitPath: false,
  value: 'code', //指定选项的值为addresslist对象的code属性
  label: 'name', //指定选项标签为addresslist对象的name属性
  children: 'children' //指定选项的子选项为addresslist对象的children属性
});

/** 查询班级管理列表 */
const getClassList = async (id) => {
  const res = await listClasses({pageNum: 1,pageSize: 100,deptId:id});
  classOptions.value = res.rows; //班级数据
}

// 根据 districtId 查找对应的完整地址路径，跳过市辖区
const getFullAddress = (districtId) => {
  const findDistrict = (list, id, path = []) => {
    for (let item of list) {
      if (item.code === id) {
        path.push(item.name);
        return path.join('/');
      }
      if (item.children && item.children.length > 0) {
        if (item.name !== '市辖区') {
          path.push(item.name);
        }
        const result = findDistrict(item.children, id, path);
        if (result) {
          return result;
        }
        if (item.name !== '市辖区') {
          path.pop(); // 回溯
        }
      }
    }
    return null;
  };

  const address = findDistrict(addRessList.value, districtId);
  return address || '未知';
};

function deptChange(e){
  //清空班级列表中的值
  data.form.classId = undefined;
  getClassList(e);
}

// /** 下载模板操作 */
// const importTemplate = () => {
//   proxy?.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
// };
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}
/** 查询学校列表 */
const getSchoolList = async () => {
  const res = await listDept();
  const data = proxy?.handleTree<DeptOptionsType>(res.data, 'deptId');
  if (data) {
    deptOptions.value = data;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  proxy?.$router.go(-1);
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  studentFormRef.value?.resetFields();
};

/** 提交按钮 */
const submitForm = () => {
  studentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      //如果当前登录用户是管理员，学校用选择字段；
      if(userId.value === 1 && tenantDisabled.value){

      }else{ 
        //是租户，学校默认传当前用户tenantId
        form.value.deptId = tenantId;
      }
      console.log('提交',userId.value,tenantDisabled.value,form.value.deptId)

      if (formId.value) {
        await updateStudent(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('编辑成功');
      } else {
        await addStudent(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('新增成功');
      }
      proxy?.$router.go(-1);
    }
  });
};

/** 获取数据 */
(async () => {
  formId.value = route.query && (route.query.id as string);
  type.value = route.query && (route.query.type as string);
  if (type.value == '0') {
    title.value = '新增';
  } else if (type.value == '1') {
    title.value = '编辑';
  } else {
    title.value = '查看';
  }
  if (formId.value) {
    const res = await getStudent(formId.value);
    //根据学校显示班级
    if(res.data.deptId){
      getClassList(res.data.deptId);
    }
    
    Object.assign(form.value, res.data);
  }
  getSchoolList();
  // fetchClasslList();
})();

</script>
<style lang="scss" scoped>
.viewBox {
  margin: 15px 15px 80px 15px;
  .title-item {
    display: flex;
    align-items: center;
    height: 24px;
    line-height: 24px;
    font-size: 20px;
    margin: 30px 0 20px;
    span {
      display: inline-block;
      margin: 0 5px;
    }
    .line-box {
      width: 4px;
      height: 24px;
      background: #05afea;
    }
  }
  .topTit {
    margin-top: 10px;
  }
  .el-form-item--default {
    margin: 15px 30px;
  }
  :deep(.el-textarea__inner) {
    width: 300px !important;
  }
  .el-input {
    width: 300px;
  }
  .el-select {
    width: 300px;
  }
  .dialog-footer {
    margin-top: 100px;
    text-align: center;
  }
}

.imgView-box {
  :deep(.el-upload-list--picture-card .el-upload-list__item-actions .el-upload-list__item-delete) {
    display: none !important;
  }
  :deep(.el-upload--picture-card) {
    display: none !important;
  }

  :deep(.el-upload-list__item.is-success .el-upload-list__item-status-label),
  :deep(.el-icon--close-tip),
  :deep(.el-icon--close) {
    display: none !important;
  }
}
</style>
